package com.hitalkie.teacher.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hitalkie.teacher.R;
import com.hitalkie.teacher.app.TalkieApi;
import com.hitalkie.teacher.fragment.LoadingDialogFragment;
import com.hitalkie.teacher.model.BaseResponse;
import com.hitalkie.teacher.model.Evaluation;
import com.hitalkie.teacher.model.Lesson;
import com.hitalkie.teacher.model.User;
import com.hitalkie.teacher.util.OkHttpManager;
import com.squareup.picasso.Picasso;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Date 30/09/2016
 *
 * @author charliema
 */

public class EvaluationActivity extends BaseActivity {

    public static final String EXTRA_LESSON = "com.hitalkie.talkie.extra.LESSON";
    public static final String EXTRA_TEACHER = "com.hitalkie.talkie.extra.TEACHER";
    public static final String EXTRA_VIP = "com.hitalkie.talkie.extra.VIP";

    private Lesson mLesson;
    private User mTeacher;
    private User mVip;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
        getData();
        updateView();
    }

    private void initData() {
        mLesson = (Lesson) getIntent().getSerializableExtra(EXTRA_LESSON);
        mTeacher = (User) getIntent().getSerializableExtra(EXTRA_TEACHER);
        mVip = (User) getIntent().getSerializableExtra(EXTRA_VIP);
    }

    private void initView() {
        setContentView(R.layout.view_evaluation);
        initTitleBar();
        ((SeekBar) findViewById(R.id.sbFluency)).setMax(100);
        ((SeekBar) findViewById(R.id.sbPronunciation)).setMax(100);
        ((SeekBar) findViewById(R.id.sbListening)).setMax(100);

        findViewById(R.id.tvConfirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                evaluate();
            }
        });
    }

    private void initTitleBar() {
        findViewById(R.id.viewTitleBarLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }

    private void getData() {

    }

    private void updateView() {
       if (mVip != null && mVip.avatar != null) {
            ImageView ivAvatar = (ImageView) findViewById(R.id.ivAvatar);
            Picasso.with(ivAvatar.getContext()).load(mVip.avatar)
                    .placeholder(R.drawable.ic_default_avatar)
                    .error(R.drawable.ic_default_avatar)
                    .fit().centerCrop().into(ivAvatar);
        }
        if (mVip != null) {
            TextView tvUserName = (TextView) findViewById(R.id.tvUserName);
            tvUserName.setText(mVip.name);
        }
    }

    private void evaluate() {
        // assemble
        int fluency = ((SeekBar) findViewById(R.id.sbFluency)).getProgress();
        int pronunciation = ((SeekBar) findViewById(R.id.sbPronunciation)).getProgress();
        int listening = ((SeekBar) findViewById(R.id.sbListening)).getProgress();

        if (fluency == 0 || pronunciation == 0 || listening == 0) {
            Toast.makeText(getActivity(), getText(R.string.can_not_be_null), Toast.LENGTH_LONG).show();
            return;
        }

        EditText etDetail = (EditText) findViewById(R.id.etDetail);
        String detail = etDetail.getText().toString();
        if (TextUtils.isEmpty(detail)) {
            etDetail.setError(getText(R.string.can_not_be_null));
            return;
        }

        Evaluation evaluation = new Evaluation();
        evaluation.lesson_id = mLesson.id;
        evaluation.student_id = mVip.id;
        evaluation.teacher_id = mTeacher.id;
        evaluation.fluency = fluency;
        evaluation.listening = listening;
        evaluation.pronunciation = pronunciation;
        evaluation.detail = detail;

        evaluate(evaluation);
    }

    private void evaluate(Evaluation evaluation) {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");
        String url = TalkieApi.getHost() + TalkieApi.PATH_EVALUATION;
        Request.Builder reqBuilder = new Request.Builder().url(url);
        reqBuilder.post(RequestBody.create(OkHttpManager.JSON, new Gson().toJson(evaluation)));
        OkHttpManager.client.newCall(reqBuilder.build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                Toast.makeText(getActivity(), getText(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        // loading dialog
                        loadingDialogFragment.dismiss();
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "evaluation resp:" + jsonStr);

                        try {
                            final BaseResponse resp = new Gson().fromJson(jsonStr, BaseResponse.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
                                        Toast.makeText(getActivity(), "打分成功", Toast.LENGTH_LONG).show();
                                        getActivity().finish();
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            new Handler(getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getActivity(), "无法解析返回的数据", Toast.LENGTH_LONG).show();
                                }
                            });
                        } finally {
                            new Handler(getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                }
                            });
                        }
                    }
                });
    }


}
